const moment = require('../../utils/moment')

// pages/ranking/ranking.js
let app = getApp()
// 获取云数据库引用
const db = wx.cloud.database()
const admin = db.collection('adminlist')
const MAX_LIMIT = 20
let today = 0

Page({

  /**
   * 页面的初始数据
   */
  data: {
    adminList: [],
    showList: [],
    type: '月榜',
    loading: true,
    date: moment().format('YYYY-MM') + '-01 至 ' + moment().format('YYYY-MM-DD')
  },

  compare (key) {
    return function (value1, value2) {
      return value2[key] - value1[key]
    }
  },

  async getAll (callback) {
    let that = this
    admin.count().then(async (res) => {
      let total = res.total
      // 计算需分几次取
      const batchTimes = Math.ceil(total / MAX_LIMIT)
      // 承载所有读操作的 promise 的数组
      for (let i = 0; i < batchTimes; i++) {
        await admin.skip(i * MAX_LIMIT).limit(MAX_LIMIT)
          .get()
          .then(async (res) => {
            let newData = res.data
            let oldData = that.data.adminList
            that.setData({
              adminList: oldData.concat(newData)
            })
          })
      }
      callback && callback()
    })
  },

  // 获取总排名
  getAllUsers () {
    let rankingList = this.data.adminList.sort(this.compare('score'))
    rankingList = rankingList.filter((item) => item.score > 0)
    this.setData({
      showList: rankingList,
      loading: false
    })
  },

  // 获取月排名
  getMonthUsers () {
    let adminList = this.data.adminList
    let newAdminList = []
    for (let i = 0; i < adminList.length; i++) {
      let signUp = adminList[i].signUp
      let newSignUp = []
      let count = 0
      for (let j = 0; j < signUp.length; j++) {
        if (signUp[j] > today && signUp[j] < today + 100) {
          newSignUp[count] = signUp[j]
          count++
        }
      }
      if (count) {
        newAdminList.push({ turename: adminList[i].turename, score: count, username: adminList[i].username })
      }
    }
    let rankingList = newAdminList.sort(this.compare('score'))
    this.setData({
      showList: rankingList,
      loading: false
    })
  },

  // 获取月榜
  toMonth: function () {
    this.setData({
      type: '月榜',
      showList: [],
      date: moment().format('YYYY-MM') + '-01 至 ' + moment().format('YYYY-MM-DD')
    })
    this.getMonthUsers()
  },

  // 获取总榜
  toAll: function () {
    this.setData({
      type: '总榜',
      showList: [],
      date: '截止 ' + moment().format('YYYY-MM-DD')
    })
    this.getAllUsers()
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getAll(() => this.getMonthUsers())
    // 获取当前年月
    today = parseInt(moment().format('YYYYMM') + '00')
  }

})